package behaviors
{
	import events.SongInfoEvent;
	
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.ProgressEvent;
	import flash.events.TimerEvent;
	import flash.media.ID3Info;
	import flash.media.Sound;
	import flash.net.URLRequest;
	import flash.utils.Timer;
	
	public class SongInfoLoader extends EventDispatcher
	{
		
		private var sound:Sound;
		private var id3Loaded:Boolean;
		private var isLoading:Boolean;
		private var progressTimer:Timer;
		private var callBack:Object;
		
		public function SongInfoLoader(url:String,callBack:Object)
		{
			id3Loaded = false;
			isLoading = false;
			this.callBack = callBack;
			this.sound = new Sound(new URLRequest(url));
			this.progressTimer = new Timer(10);
			this.sound.addEventListener(Event.ID3,handleID3);
			this.sound.addEventListener(ProgressEvent.PROGRESS,handleProgressEvent);
			this.progressTimer.addEventListener(TimerEvent.TIMER,onTick);
			progressTimer.start();
		}
		
		private function handleProgressEvent(event:Event):void{
			sound.removeEventListener(ProgressEvent.PROGRESS,handleProgressEvent);
			isLoading = true;
		}
		
		
		private function handleID3(event:Event):void{
			id3Loaded = true;
			sound.removeEventListener(Event.ID3,handleID3);
		}
		
		public function onTick(event:TimerEvent):void
		{
			if(sound!=null){
				if(id3Loaded && isLoading){
					if(sound.bytesLoaded>sound.bytesTotal*0.12){
						trace("Finish");
						progressTimer.removeEventListener(TimerEvent.TIMER,onTick);
						calcData();
					}
				}
			}
		}
		
		public function calcData():void{
			var id3:ID3Info = sound.id3;
			var songNameStr:String = id3.songName==null ? "" : id3.songName;
			var artistStr:String = id3.artist==null ? "" : id3.artist;
			var pathStr:String = sound.url==null ? "" : sound.url;
			var genreStr:String = id3.genre==null ? "" : id3.genre;
			var albumStr:String = id3.album==null ? "" : id3.album;
			var durationNumber:int = (sound.bytesTotal / (sound.bytesLoaded / sound.length)) / 1000;
			var timeStr:String = parseTime(durationNumber);
			var songObj:Object = {name:songNameStr,artist:artistStr,title:artistStr+" - "+songNameStr,
				path:pathStr,genre:genreStr,album:albumStr,duration:durationNumber,time:timeStr,mark:1};
			var songInfoEvent:SongInfoEvent = new SongInfoEvent(songObj);
			
			callBack.addSong(songObj);;
		}
		
		private function millsToSeconds(mills:Number):Number{
			return Math.floor(mills/1000);
		}
		
		private function parseTime(seconds:Number):String {
			var secondsStr:String = new String();
			var min:Number = Math.floor(seconds/60);
			var sec:Number = Math.floor(seconds%60);
			secondsStr = min + ":" + ((sec<10) ? ("0" + sec) : sec); 
			return secondsStr;
		}
	}
}